package com.hcb.micro.util;

import java.security.MessageDigest;
import com.alibaba.fastjson.JSONObject;
import com.hcb.micro.cache.memcache.CacheManager;
import com.hcb.micro.cache.memcache.CacheServiceIF;

public class WeixinMessageDigestUtil {
	
	private static final WeixinMessageDigestUtil _instance = new WeixinMessageDigestUtil();
	
	private MessageDigest alga;
	
	private static CacheServiceIF cache = CacheManager.getClient("memcache");
	
	private WeixinMessageDigestUtil()
    {
        try
        {
            alga = MessageDigest.getInstance("SHA-1");
        }
        catch (Exception e)
        {
            throw new InternalError("init MessageDigest error:" + e.getMessage());
        }
    }
	
	public static WeixinMessageDigestUtil getInstance()
    {
        return _instance;
    }
	
	/**
     * 获取公众账号accessToken
     * @param host
     * @param params
     * @return
     * @return
     */
    public static String getAccessToken(String appid, String secret){
        Object cdeCache = cache.get(CacheConstant.HQBS_TOKEN_CACHE);
        String accessToken = null;
        if (cdeCache != null){
            accessToken = (String)cdeCache;
        }else{
            JSONObject parameters = new JSONObject();
            parameters.put("grant_type", "client_credential");
            parameters.put("appid",appid);
            parameters.put("secret",secret );
            JSONObject j = (JSONObject)CommonHttpClient.commonHTTP("get", "https://api.weixin.qq.com/cgi-bin/token", parameters);
            if (j.getString("errcode") != null){
            }else{
                accessToken = j.getString("access_token");
            }
            cache.set(CacheConstant.HQBS_TOKEN_CACHE, accessToken, CacheConstant.CACHE_HOUR_1);
        }
        return accessToken;
    }
}
